package com.lcy.proto.server;

import com.lcy.proto.rpc.Params;
import com.lcy.proto.rpc.RequestWrapper;
import com.lcy.proto.rpc.Result;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author loucy
 * @version 1.0
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(12356));
        SocketChannel channel = serverSocketChannel.accept();
        while (true){
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            channel.read(buffer);
            buffer.flip();
            byte[] bytes = new byte[buffer.limit()];
            buffer.get(bytes);
            RequestWrapper wrapper = RequestWrapper.newBuilder()
                    .mergeFrom(bytes)
                    .build();
            Params params = wrapper.getParams();
            Result.Builder builder = Result.newBuilder();
            switch (wrapper.getMethod()) {
                case "add":
                    builder.setResult(params.getParam1()+params.getParam2());
                    break;
                case "sub":
                    builder.setResult(params.getParam1()-params.getParam2());
                    break;
            }
            System.out.println(params);
            System.out.println(builder.build());
            byte[] result = builder.build().toByteArray();
            ByteBuffer sendBuffer = ByteBuffer.allocate(result.length);
            sendBuffer.put(result);
            sendBuffer.flip();
            channel.write(sendBuffer);
        }
    }
}
